#nullable enable

using Application.Service.Auth;
using Application.Service.Users;

using Microsoft.AspNetCore.Components;

using System;
using System.Threading.Tasks;

namespace Application.Web.Core.Services;

/// <summary>
/// 前端权限检查服务
/// <para>功能：提供前端页面和操作的权限检查功能</para>
/// <list type="bullet">
/// <item><description>页面访问权限检查</description></item>
/// <item><description>操作权限验证</description></item>
/// <item><description>超级管理员权限判断</description></item>
/// <item><description>只读用户权限判断</description></item>
/// <item><description>无权限页面重定向</description></item>
/// </list>
/// </summary>
public class CheckPermission
{
    private readonly AuthService _authService;
    private readonly PermissionCheckService _permissionCheckService;
    private readonly NavigationManager _navigationManager;

    public CheckPermission(AuthService authService, PermissionCheckService permissionCheckService, NavigationManager navigationManager)
    {
        _authService = authService;
        _permissionCheckService = permissionCheckService;
        _navigationManager = navigationManager;
    }

    /// <summary>
    /// 检查当前用户是否拥有特定权限
    /// </summary>
    /// <param name="permissionCode">权限编码</param>
    /// <returns>权限检查结果</returns>
    public async Task<(bool hasPermission, bool isReadOnly)>
        CheckCurrentUserPermissionAsync(string permissionCode)
    {
        if (!_authService.IsAuthenticated)
            return (false, false);

        var userId = await GetCurrentUserIdAsync();
        if (userId <= 0)
            return (false, false);

        return await _permissionCheckService.CheckPermissionAsync(userId, permissionCode);
    }

    /// <summary>
    /// 检查当前用户是否可以访问特定页面
    /// </summary>
    /// <param name="pageCode">页面编码</param>
    /// <returns>是否可以访问</returns>
    public async Task<bool> CanAccessPageAsync(string pageCode)
    {
        if (!_authService.IsAuthenticated)
            return false;

        var userId = await GetCurrentUserIdAsync();
        if (userId <= 0)
            return false;

        // 超级管理员可以访问所有页面
        if (await _permissionCheckService.IsSuperAdminAsync(userId))
            return true;

        var (canAccess, _) = await _permissionCheckService.CheckPageAccessAsync(userId, pageCode);
        return canAccess;
    }

    /// <summary>
    /// 检查当前用户是否可以执行特定操作
    /// </summary>
    /// <param name="operationCode">操作编码</param>
    /// <returns>是否可以执行</returns>
    public async Task<bool> CanPerformOperationAsync(string operationCode)
    {
        if (!_authService.IsAuthenticated)
            return false;

        var userId = await GetCurrentUserIdAsync();
        if (userId <= 0)
            return false;

        // 超级管理员可以执行所有操作
        if (await _permissionCheckService.IsSuperAdminAsync(userId))
            return true;

        // 检查操作权限
        return await _permissionCheckService.CheckOperationPermissionAsync(userId, operationCode);
    }

    /// <summary>
    /// 检查当前用户是否拥有页面只读权限
    /// </summary>
    /// <param name="pageCode">页面编码</param>
    /// <returns>是否为只读权限</returns>
    public async Task<bool> IsPageReadOnlyAsync(string pageCode)
    {
        if (!_authService.IsAuthenticated)
            return true;

        var userId = await GetCurrentUserIdAsync();
        if (userId <= 0)
            return true;

        // 超级管理员拥有完整权限
        if (await _permissionCheckService.IsSuperAdminAsync(userId))
            return false;

        var (canAccess, isReadOnly) = await _permissionCheckService.CheckPageAccessAsync(userId, pageCode);
        return canAccess && isReadOnly;
    }

    /// <summary>
    /// 重定向到无权限页面或登录页面
    /// </summary>
    public void RedirectToNoPermission()
    {
        if (!_authService.IsAuthenticated)
        {
            _navigationManager.NavigateTo("/login");
        }
        else
        {
            _navigationManager.NavigateTo("/no-permission");
        }
    }

    /// <summary>
    /// 获取当前用户ID
    /// </summary>
    /// <returns>用户ID</returns>
    private async Task<int> GetCurrentUserIdAsync()
    {
        if (!_authService.IsAuthenticated)
            return -1;

        var user = await _authService._userService.GetAsync(_authService.Username);
        return user?.Id ?? -1;
    }

    /// <summary>
    /// 检查当前用户是否为超级管理员
    /// </summary>
    /// <returns>是否为超级管理员</returns>
    public async Task<bool> IsCurrentUserSuperAdminAsync()
    {
        if (!_authService.IsAuthenticated)
            return false;

        var userId = await GetCurrentUserIdAsync();
        return await _permissionCheckService.IsSuperAdminAsync(userId);
    }

    /// <summary>
    /// 检查当前用户是否为只读用户
    /// </summary>
    /// <returns>是否为只读用户</returns>
    public async Task<bool> IsCurrentUserReadOnlyAsync()
    {
        if (!_authService.IsAuthenticated)
            return false;

        var userId = await GetCurrentUserIdAsync();
        return await _permissionCheckService.IsReadOnlyUserAsync(userId);
    }
}